import os
import time
import datetime
import serial

DEVICE_PATH = "/dev/serial/by-id/usb-Arduino_RaspberryPi_Pico_615044501C854018-if00"  # 设备路径
BAUD_RATE = 115200           # 波特率
TIMEOUT = 1                  # 超时时间（秒）

def is_device_connected():
    """检查设备是否连接"""
    return os.path.exists(DEVICE_PATH)
def get_filename():
    now = datetime.datetime.now()
    return f"/mnt/smb_share/amslog/data_{now.strftime('%Y-%m-%d_%H')}.txt"
def main():
    global last_time
    last_time = time.time()
    print("等待设备连接...")
    ser = None

    current_file = get_filename()
    print(f"Writing to file: {current_file}")
    while True:
        # 检查日期是否改变
        new_file = get_filename()
        if new_file != current_file:
            print(f"Switching to new file: {new_file}")
            current_file = new_file
        try:
            if is_device_connected():
                if ser is None or not ser.is_open:
                    # 打开串口
                    print(f"设备已连接: {DEVICE_PATH}")
                    ser = serial.Serial(DEVICE_PATH, BAUD_RATE, timeout=TIMEOUT)
                    print("串口已打开，开始处理数据...")

                # 从设备读取数据
                if ser.in_waiting > 0:
                    data = ser.read(ser.in_waiting)
                    hex_data = ' '.join(f'{byte:02X}' for byte in data)
                    
                    # 获取当前时间
                    current_time = time.time()
                    if current_time - last_time >= 60:
                        # 更新last_time
                        last_time = current_time
                        with open(current_file, 'a') as file:
                            # 写入当前时间戳
                            timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time))
                            file.write(f"\n--- 数据开始: {timestamp} ---")  # Write the hex data followed by a newline
                    else:
                        if not os.path.exists(current_file):
                            with open(current_file, 'a') as file:
                                # 写入当前时间戳
                                timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time))
                                file.write(f"\n--- 数据开始: {timestamp} ---")  
                    # Write the hex data followed by a newline
                    # 将数据写入文件
                    with open(current_file, 'a') as file:
                       file.write(hex_data + ' ')  # Write the hex data followed by a newline

                # 每过一分钟，换一行并写入时间戳
            else:
                # 如果设备断开
                if ser and ser.is_open:
                    print("设备断开，关闭串口...")
                    ser.close()
                print("等待设备连接...")
                time.sleep(2)

        except serial.SerialException as e:
            print(f"串口错误: {e}")
            if ser and ser.is_open:
                ser.close()
        except KeyboardInterrupt:
            print("程序终止...")
            if ser and ser.is_open:
                ser.close()
            break

if __name__ == "__main__":
    main()
